﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Zen.Barcode;

namespace Worktool
{
    public partial class IpDevices : Form
    {
        String pkInstalledPrinters;
        PrintDocument label;        
        
        private string labelSerialNumber = "";
        private string labelManufacturer = "";
        private string labelModel = "";
        private string labelPosition = "";
        private string labelVenue = "";
        private string labelJLM = "";
        private string labelTa1 = "";
        private string labelTa2 = "";
        private string labelTa3 = "";

        public IpDevices()
        {
            InitializeComponent();
            this.Text = "IP Devices: " + Properties.Settings.Default.CurrentDBName; 
            this.dataGridView1.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellValueChanged);          
        }

        private void IpDevices_Load(object sender, EventArgs e)
        {
            // TODO: Diese Codezeile lädt Daten in die Tabelle "aSCDataSet.STAMMDATEN_systemID". Sie können sie bei Bedarf verschieben oder entfernen.
            this.sTAMMDATEN_systemIDTableAdapter.Fill(this.aSCDataSet.STAMMDATEN_systemID);
            // Update Devicelist aus Material Detail
            this.vw_eng_IpDevicesTableAdapter.updateIpDevices();
            this.vw_eng_IpDevices_ManufacturerTableAdapter.Fill(this.aSCDataSet.vw_eng_IpDevices_Manufacturer);
            this.vw_eng_IpDevicesTableAdapter.Fill(this.aSCDataSet.vw_eng_IpDevices);
            //label2.Text = dataGridView1.RowCount.ToString();
            comboBox1.Text = "";
            comboBox2.Text = "";
            this.vwengIpDevicesBindingSource.Filter = string.Format("Manufacturer LIKE '{0}'", (comboBox1.Text + "*"));

            // Drucker in das Auswahlfeld eintragen
            for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
            {
                pkInstalledPrinters = PrinterSettings.InstalledPrinters[i];
                comboBox3.Items.Add(pkInstalledPrinters);
            }
            for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
            {
                if (Properties.Settings.Default.LabelPrinterName == PrinterSettings.InstalledPrinters[i])
                {
                    comboBox3.Text = Properties.Settings.Default.LabelPrinterName;
                }
            }
            
        }

        //
        // Update to Database after CellValuechanged
        //
        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex != dataGridView1.Columns["updateDate"].Index || e.ColumnIndex != dataGridView1.Columns["updateUser"].Index)
            {
                try
                {
                    dataGridView1.CurrentRow.Cells["updateDate"].Value = DateTime.Today;
                    dataGridView1.CurrentRow.Cells["updateUser"].Value = Properties.Settings.Default.User;
                    this.vwengIpDevicesBindingSource.EndEdit();
                    vw_eng_IpDevicesTableAdapter.Update(aSCDataSet);
                    
                }
                catch (Exception ex)
                {
                }
            }
        }      

        //
        // Export to Excel
        //
        private void pictureBox2_Click(object sender, EventArgs e)
        {
            dataGridView1.SelectAll();
            DataObject dataObj = dataGridView1.GetClipboardContent();
            if (dataObj != null)
                Clipboard.SetDataObject(dataObj);
            Microsoft.Office.Interop.Excel.Application xlexcel;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            xlexcel = new Microsoft.Office.Interop.Excel.Application();
            xlexcel.Visible = true;
            xlWorkBook = xlexcel.Workbooks.Add(misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
            CR.Select();
            xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
            dataGridView1.ClearSelection();
        }

        private void copyValueToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedCells.Count == 1)
            {
                Clipboard.SetText(dataGridView1.SelectedCells[0].Value.ToString());
            }
        }

        private void pasteValueToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Clipboard.GetText() != "")
            {
                for (int i = 0; i < dataGridView1.SelectedCells.Count; i++)
                {
                    try
                    {
                        dataGridView1.CurrentRow.Cells["updateDate"].Value = DateTime.Today;
                        dataGridView1.CurrentRow.Cells["updateUser"].Value = Properties.Settings.Default.User;
                        dataGridView1.SelectedCells[i].Value = Clipboard.GetText();                    
                    }
                    catch (Exception ex)
                    { }
                }
            }
        }

        private void deleteValueToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedCells.Count != 0)
            {
                for (int i = 0; i < dataGridView1.SelectedCells.Count; i++)
                {
                    try
                    {
                        if (dataGridView1.SelectedCells[i].ValueType == typeof(string))
                        {
                            dataGridView1.SelectedCells[i].Value = "";
                        }
                        if (dataGridView1.SelectedCells[i].ValueType == typeof(int))
                        {
                            dataGridView1.SelectedCells[i].Value = 0;
                        }
                    }
                    catch (Exception ex)
                    { }
                }
            }
        }

        private void insertAscendingIPsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            List<int> reihen = new List<int> { };
            int spalte = 0;
            int ip=0;
            int chosenCells = 0;
            string praefix = "";
            string suffix = "";

            chosenCells = dataGridView1.SelectedCells.Count;
            if (chosenCells > 1)
            {
                spalte = dataGridView1.SelectedCells[0].ColumnIndex;
                for (int y = 0; y < chosenCells; y++)
                {
                    reihen.Add(dataGridView1.SelectedCells[y].RowIndex);
                }
                reihen.Sort();
                praefix = dataGridView1[spalte, reihen[0]].Value.ToString().Substring(0,dataGridView1[spalte, reihen[0]].Value.ToString().LastIndexOf(".")+1);
                suffix = dataGridView1[spalte, reihen[0]].Value.ToString().Substring(dataGridView1[spalte, reihen[0]].Value.ToString().LastIndexOf(".") + 1);
                if(int.TryParse(suffix,out ip))
                {
                    for (int i = 1; i < chosenCells; i++)
                    {
                        ip++;
                        dataGridView1[spalte, reihen[i]].Value = praefix + ip.ToString();
                        
                        
                    }
                }
            }
        }

        private void insertDescendingIPsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            List<int> reihen = new List<int> { };
            int spalte = 0;
            int ip = 0;
            int chosenCells = 0;
            string praefix = "";
            string suffix = "";

            chosenCells = dataGridView1.SelectedCells.Count;
            if (chosenCells > 1)
            {
                spalte = dataGridView1.SelectedCells[0].ColumnIndex;
                for (int y = 0; y < chosenCells; y++)
                {
                    reihen.Add(dataGridView1.SelectedCells[y].RowIndex);
                }
                reihen.Sort();
                praefix = dataGridView1[spalte, reihen[0]].Value.ToString().Substring(0, dataGridView1[spalte, reihen[0]].Value.ToString().LastIndexOf(".") + 1);
                suffix = dataGridView1[spalte, reihen[0]].Value.ToString().Substring(dataGridView1[spalte, reihen[0]].Value.ToString().LastIndexOf(".") + 1);
                if (int.TryParse(suffix, out ip))
                {
                    for (int i = 1; i < chosenCells; i++)
                    {
                        ip--;
                        dataGridView1[spalte, reihen[i]].Value = praefix + ip.ToString();


                    }
                }
            }
        }

        //
        // Filter List
        //
        private void comboBox_TextChanged(object sender, EventArgs e)
        {
            try
            {

                if (comboBox1.Text == "" && comboBox2.Text == "")
                {
                    vwengIpDevicesBindingSource.Filter = "";

                }
                else if (comboBox1.Text != "" && comboBox2.Text == "")
                {
                    vwengIpDevicesBindingSource.Filter = string.Format("Manufacturer LIKE '{0}'", comboBox1.Text+"*");

                }
                else if (comboBox1.Text == "" && comboBox2.Text != "")
                {
                    vwengIpDevicesBindingSource.Filter = string.Format("Sparte LIKE '{0}'", comboBox2.Text+"*");
                }
                else if (comboBox1.Text != "" && comboBox2.Text != "")
                {
                    vwengIpDevicesBindingSource.Filter = string.Format("Manufacturer LIKE '{0}' AND Sparte LIKE '{1}'", comboBox1.Text+"*", comboBox2.Text+"*");
                }

            }
            catch (Exception ex)
            {
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            dataGridView1.SelectAll();
            DataObject dataObj = dataGridView1.GetClipboardContent();
            if (dataObj != null)
                Clipboard.SetDataObject(dataObj);
            Microsoft.Office.Interop.Excel.Application xlexcel;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            xlexcel = new Microsoft.Office.Interop.Excel.Application();
            xlexcel.Visible = true;
            xlWorkBook = xlexcel.Workbooks.Add(misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
            CR.Select();
            xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
            dataGridView1.ClearSelection();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count != 0)
            {
                
                // Zugehöriges Label ausdrucken
                  

                label = new PrintDocument();
                PaperSize pS = new PaperSize("Custom Size", 620, 620);
                label.DefaultPageSettings.PaperSize = pS;
                label.PrinterSettings.PrinterName = comboBox3.Text;
                label.PrinterSettings.DefaultPageSettings.PaperSize = pS;
                label.PrintPage += new PrintPageEventHandler(label_PrintPage);

                label.Print();
                
               
            }
        }

        private void label_PrintPage(object sender, PrintPageEventArgs e)
        {

            SolidBrush brush = new SolidBrush(Color.Black);
            System.Drawing.Font header = new System.Drawing.Font(FontFamily.GenericSansSerif, 8.0F, FontStyle.Bold);
            Code128BarcodeDraw barcode128 = BarcodeDrawFactory.Code128WithChecksum;
            int x = 5;
            //Image img;


            for (int i = 0; i < dataGridView1.ColumnCount; i++)
            {
                if (dataGridView1.SelectedRows[0].Cells[i].Value.ToString() != "")
                {
                    e.Graphics.DrawString((dataGridView1.Columns[i].HeaderText.ToString() + ": " + dataGridView1.SelectedRows[0].Cells[i].Value.ToString()), header, brush, 5, x);
                    x += 12;
                }
            }

            //labelModel = dataGridView1.SelectedRows[0].Cells["Model"].Value.ToString(); 
            //e.Graphics.DrawString("Model: " + labelModel, header, brush, 5, 5);

            e.Graphics.DrawImage(Worktool.Properties.Resources.ASC_Logo_quadratisch, 200, 10, 30, 30);
            //if (labelSerialNumber != null && labelSerialNumber != "")
            //{
            //    img = barcode128.Draw(labelSerialNumber, 30);
            //    e.Graphics.DrawImage(img, 5, 113);
            //}



        }
        
    }
}
